﻿using Bigway.Common.Models.DbModels;

namespace Bigway.Common.Services.Repositories;

public class BaseSqliteEntityRepository<TEntity>(IServiceProvider sp) :
    BaseSqliteRepository<TEntity>(sp), IBaseSqliteEntityRepository<TEntity>
    where TEntity : BaseEntity, new()
{
    public virtual async Task<TEntity?> GetByIdAsync(string id, CancellationToken token = default)
    {
        return await Queryable.FirstAsync(x => x.Id == id, token);
    }

    public virtual async Task UpdateAsync(TEntity entity,
        DateTime? updateTime,
        CancellationToken token = default)
    {
        entity.UpdateTime = updateTime ?? DateTime.UtcNow;
        await Db.Updateable(entity).ExecuteCommandAsync(token);
    }

    public virtual async Task UpdateAllAsync(List<TEntity> entities,
        DateTime? updateTime,
        CancellationToken token = default)
    {
        var actualUpdateTime = updateTime ?? DateTime.UtcNow;
        foreach (var entity in entities)
        {
            entity.UpdateTime = actualUpdateTime;
        }
        await Db.Updateable(entities).ExecuteCommandAsync(token);
    }
}